var randomID = (new Date()).valueOf();;
var config = {
    /** 用户授权配置 */
    authConfig: {
        // REST API 访问地址 https://console.easemob.com/app/im-service/detail 
        baseUrl : 'a1.easemob.com', 
        // APPKEY https://console.easemob.com/app/applicationOverview/detail 
        orgName : '1113181124010841', 
        // APPKEY https://console.easemob.com/app/applicationOverview/detail 
        appName : 'cloudstudio',    

        clientId: 'YXA6KMsxsO--EeiNQJmhf8gr3w',

        clientSecret: 'YXA6FBHoX7zcDwmO49D6PB7AbB3TjqY',
    },

    /** 连接配置 */
    connectConfig:{
        //  连接地址 https://console.easemob.com/app/generalizeMsg/overviewService
        host : 'rmwzi0.cn1.mqtt.chat', 
        // WebSocket 协议服务端口，如果是走 HTTPS，设置443端口
        port: 443 ,     
        // APPID  https://console.easemob.com/app/generalizeMsg/overviewService 
        appId: 'rmwzi0',  
        //  用户自定义deviceID
        deviceId :'device_'+randomID,
        // clientId 格式 deviceID@AppID
        clientId : 'device_'+randomID+'@rmwzi0', //

        // 是否走加密 HTTPS，如果走 HTTPS，设置为 true
        useTLS : true, 
        // cleansession标志
        cleanSession : true, 
        // 超时重连时间
        reconnectTimeout : 2000, 
        // 请求超时时间
        timeout: 2, 
        // mqtt版本号
        mqttVersion: 4, 
    },
}
var client = new easemobMQTT(config);
var username = 'user';
var password = 'user';
var clientId = 'device_'+randomID;
var topic = 'topic/mutual';
    // 收到别人的信息后,生成别人
    client.onMessageArrived = function(message){
        var _topic = message.destinationName
        var receive_content = message.payloadString
        var receive_content = JSON.parse(receive_content);
        var obj = $('#'+receive_content.user);
       
        if(receive_content.user == clientId){
            return ; 
        }
        //  接收消息后,更新坐标信息,如果已经存在元素,则更新元素坐标,如果不存在,则新增元素,并更新坐标
        if($(obj).length == 0 ){
            html = '<div id="'+receive_content.user+'" \
                        title="'+receive_content.user+'" \
                        class="'+receive_content.class+'" \
                        data-deadline="'+getTimestamp(60)+'" \
                    ></div>';
            $('#public').append(html);
            obj = $('#'+receive_content.user);
        }else{
            $(obj).attr('title',receive_content.user);
            $(obj).attr('class',receive_content.class);
            $(obj).attr('data-deadline',getTimestamp(60));
        }

        // 坐标轨迹绘制
        if(receive_content.records){
            $(receive_content.records).each(function(index,item){
                setTimeout(function(){
                    $(obj).css({
                        left: item.left + 'px',
                        top: item.top + 'px',
                    });
                },parseInt(item.time));
            });
        }
        // 收到私有坐标同步请求,向单个客户端发送坐标信息
        if(receive_content.action && receive_content.action =='SYNC_POSITION' && receive_content.private != clientId){
            console.log('收到单向坐标同步请求,单向发布坐标信息');
            var position = JSON.stringify({
                'user':clientId,
                'class':$('#myshape').attr('class'),
                'records':[{
                    time:10,
                    left:$('#myshape').offset().left,
                    top:$('#myshape').offset().top,
                }],
                
            });
            client.sendMessage(receive_content.private,position);
        }

    }

    // 连接成功后,生成自己
    client.onConnectionSuccess = function(message){
        client.subscribe(topic);
        if($('#myshape').length==0){
            var obj = '<div id="myshape" \
                        title="一个大帅比" \
                        class="shape circle '+getRandomAvatar()+'" \
                    ></div>';
            $('#public').append(obj);
            setInterval("removePosition()",5000);
            setInterval("sendPosition()",5000);
        }


        // 向其他客户端要求同步一下坐标信息
        client.subscribe(clientId);
        message = JSON.stringify({
            'action':'SYNC_POSITION',
            'private':clientId,
        });
        client.sendMessage(topic,message);
        console.log('请求同步坐标消息');
    }
try{
    client.login(username,password);
    client.connect();
}catch(e){
    console.log(e);
}



// -----------拖拽-----------
var drag_h = 0;
var drag_w = 0;
var dragX = 0;
var dragY = 0;
var l = 0;
var t = 0;
var isDrag = false;
var records = [];
var recordTime = Date.now();
// div 
$('#public').on('mousedown','#myshape',function (e) {
    drag_h = $('#myshape').height();
    drag_w = $('#myshape').width();
    dragX = e.clientX - $('#myshape').offset().left;
    dragY = e.clientY - $('#myshape').offset().top;
    isDrag=true;

    records = [];
    recordTime = Date.now();

});
$(document).mousemove(function (e) {
    if(isDrag==false){
        return ;
    }
    l = e.clientX - dragX
    t = e.clientY - dragY
    $('#myshape').css({
        left: l + 'px',
        top: t + 'px',
    });
    records.push({
        time:parseInt(Date.now()) - recordTime,
        left:l,
        top:t
    });

})
$(document).mouseup(function (e) {
    isDrag = false;
    sendPosition();
})


// -----------重置-----------
$('#resetPosition').bind('click',function(e){
    resetPosition();
})

